package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存访客记录
    public void save(Visitors visitors) {
        //1、查询是否存在今日的访客数据
        Criteria criteria = Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate());
        Query query = Query.query(criteria);
        if(!mongoTemplate.exists(query,Visitors.class)) {
            //2、如果不存在，保存
            mongoTemplate.save(visitors);
        }
    }

    //根据用户id和时间查询,
    public List<Visitors> queryMyVisitors(Long userId, Long date) {
        //查询访问时间大于date
        Criteria criteria = Criteria.where("userId").is(userId).and("date").gt(date);
        Query query = Query.query(criteria).
                with(Sort.by(Sort.Order.desc("date"))).limit(5);
        return mongoTemplate.find(query,Visitors.class);
    }


    //根据用户id查询
    public List<Visitors> findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("date")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Visitors.class);
    }
}
